package com.my.home.common.scan;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.my.home.common.Base.RespJson;
import com.my.home.common.utils.WebUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义异常处理
 * Created by Al Sah-him on 2018/6/29.
 */
@Component
public class ExceptionResolver implements HandlerExceptionResolver{
    private static final Logger LOGGER= LogManager.getLogger(ExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
        LOGGER.error(e.getMessage(),e);

        //非控制器请求造成的异常
        if(!(handler instanceof HandlerMethod)){
            return new ModelAndView("error/500");
        }
        HandlerMethod handlerMethod= (HandlerMethod) handler;

        //ajax请求
        if(WebUtils.isAjax(handlerMethod)){
            return new ModelAndView(new FastJsonJsonView(),RespJson.failure(e.getMessage()));
        }
        System.out.println(e.getMessage());

        return new ModelAndView("error/500").addObject("error",e.getMessage());
    }
}
